{% extends 'base.html' %}

{% block title %}仓库管理 - 固定资产管理系统{% endblock %}

{% block content %}
<div class="row">
    <div class="col-md-12">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="{% url 'assets:index' %}">首页</a></li>
                <li class="breadcrumb-item active" aria-current="page">仓库管理</li>
            </ol>
        </nav>
        
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h2><i class="fas fa-warehouse me-2"></i>仓库管理</h2>
            <div class="btn-group">
                <a href="#" class="btn btn-primary" id="btnOpenCreateModal" data-modal-url="{% url 'assets:warehouse_create' %}" data-modal-title="新增仓库">
                    <i class="fas fa-plus me-1"></i>新增仓库
                </a>
                <button type="button" class="btn btn-outline-primary dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown">
                    <span class="visually-hidden">更多操作</span>
                </button>
                <ul class="dropdown-menu">
                    <li><a class="dropdown-item" href="{% url 'assets:consumable_list' %}">
                        <i class="fas fa-boxes me-2"></i>耗材管理
                    </a></li>
                    <li><a class="dropdown-item" href="{% url 'assets:inventory_log_list' %}">
                        <i class="fas fa-history me-2"></i>库存记录
                    </a></li>
                    <li><hr class="dropdown-divider"></li>
                    <li><a class="dropdown-item text-danger" href="#" onclick="batchDeleteWarehouses()">
                        <i class="fas fa-trash me-2"></i>批量删除
                    </a></li>
                </ul>
            </div>
        </div>
        
        <!-- 搜索和筛选 -->
        <div class="card mb-4">
            <div class="card-body">
                <form method="get" class="d-flex flex-wrap align-items-center gap-2">
                    <div style="width: 280px; min-width: 250px;">
                        <div class="input-group">
                            <input type="text" class="form-control" name="search" placeholder="搜索仓库名称..." value="{{ search_query }}">
                            <button class="btn btn-outline-secondary" type="submit">
                                <i class="fas fa-search me-1"></i>搜索
                            </button>
                        </div>
                    </div>
                    <div>
                        <button type="button" class="btn btn-outline-info btn-sm" onclick="clearSearch()">
                            <i class="fas fa-times me-1"></i>清除
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- 仓库列表 -->
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fas fa-list me-2"></i>仓库列表
                    {% if page_obj %}
                        <span class="badge bg-secondary ms-2">{{ page_obj.paginator.count }} 个仓库</span>
                    {% endif %}
                </h5>
            </div>
            <div class="card-body">
                <form id="batchDeleteForm" method="post" action="{% url 'assets:warehouse_batch_delete' %}">
                    {% csrf_token %}
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead class="table-dark">
                                <tr>
                                    <th width="5%">
                                        <input type="checkbox" class="form-check-input" id="selectAllHeader" onchange="toggleSelectAll()">
                                    </th>
                                    <th width="18%">仓库名称</th>
                                    <th width="18%">位置</th>
                                    <th width="15%">管理员</th>
                                    <th width="22%">描述</th>
                                    <th width="12%">创建时间</th>
                                    <th width="10%">操作</th>
                                </tr>
                            </thead>
                        <tbody>
                            {% for warehouse in page_obj %}
                            <tr>
                                <td>
                                    <input type="checkbox" class="form-check-input warehouse-checkbox" name="warehouse_ids" value="{{ warehouse.pk }}">
                                </td>
                                <td>
                                    <div class="d-flex align-items-center">
                                        <i class="fas fa-warehouse me-2 text-primary"></i>
                                        <strong>{{ warehouse.name }}</strong>
                                    </div>
                                </td>
                                <td>
                                    {% if warehouse.location %}
                                        <div class="d-flex align-items-center">
                                            <i class="fas fa-map-marker-alt me-1 text-success"></i>
                                            {{ warehouse.location.name }}
                                        </div>
                                    {% else %}
                                        <span class="text-muted">-</span>
                                    {% endif %}
                                </td>
                                <td>
                                    {% if warehouse.manager %}
                                        <div class="d-flex align-items-center">
                                            <i class="fas fa-user me-1 text-info"></i>
                                            {{ warehouse.manager.get_full_name|default:warehouse.manager.username }}
                                        </div>
                                    {% else %}
                                        <span class="text-muted">未指定</span>
                                    {% endif %}
                                </td>
                                <td>
                                    {% if warehouse.description %}
                                        <span title="{{ warehouse.description }}">{{ warehouse.description|truncatechars:40 }}</span>
                                    {% else %}
                                        <span class="text-muted">-</span>
                                    {% endif %}
                                </td>
                                <td>
                                    <div class="text-nowrap">
                                        <i class="fas fa-calendar me-1 text-muted"></i>
                                        {{ warehouse.created_at|date:"m-d H:i" }}
                                    </div>
                                    <small class="text-muted">{{ warehouse.created_at|date:"Y" }}</small>
                                </td>
                                <td>
                                    <div class="btn-group btn-group-sm">
                                        <a href="{% url 'assets:warehouse_detail' warehouse.pk %}" class="btn btn-outline-info" title="查看详情">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                        <a href="{% url 'assets:warehouse_update' warehouse.pk %}" class="btn btn-outline-primary" title="编辑">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                        <a href="{% url 'assets:warehouse_delete' warehouse.pk %}" class="btn btn-outline-danger" title="删除" onclick="return confirm('确定要删除仓库 {{ warehouse.name }} 吗？')">
                                            <i class="fas fa-trash"></i>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                            {% empty %}
                            <tr>
                                <td colspan="7" class="text-center py-4">
                                    <div class="text-muted">
                                        <i class="fas fa-warehouse fa-2x mb-2"></i>
                                        <p class="mb-0">暂无仓库数据</p>
                                    </div>
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </form>
        </div>
        </div>

        <!-- 分页 -->
        {% if page_obj.has_other_pages %}
        <nav aria-label="页面导航" class="mt-4">
            <ul class="pagination justify-content-center">
                {% if page_obj.has_previous %}
                    <li class="page-item">
                        <a class="page-link" href="?page={{ page_obj.previous_page_number }}{% if search_query %}&search={{ search_query }}{% endif %}">
                            <i class="fas fa-chevron-left"></i>
                        </a>
                    </li>
                {% endif %}
                
                {% for num in page_obj.paginator.page_range %}
                    {% if page_obj.number == num %}
                        <li class="page-item active">
                            <span class="page-link">{{ num }}</span>
                        </li>
                    {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
                        <li class="page-item">
                            <a class="page-link" href="?page={{ num }}{% if search_query %}&search={{ search_query }}{% endif %}">{{ num }}</a>
                        </li>
                    {% endif %}
                {% endfor %}
                
                {% if page_obj.has_next %}
                    <li class="page-item">
                        <a class="page-link" href="?page={{ page_obj.next_page_number }}{% if search_query %}&search={{ search_query }}{% endif %}">
                            <i class="fas fa-chevron-right"></i>
                        </a>
                    </li>
                {% endif %}
            </ul>
        </nav>
        {% endif %}
    
<!-- 仓库创建/编辑表单 Modal 容器 -->
<div class="modal fade" id="warehouseFormModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="warehouseFormTitle">表单</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <form id="warehouseForm" method="post">
        {% csrf_token %}
        <div class="modal-body" id="warehouseFormBody">
          <div class="text-center text-muted py-3">加载中...</div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
          <button type="submit" class="btn btn-primary">
            <i class="fas fa-save me-1"></i>保存
          </button>
        </div>
      </form>
    </div>
  </div>
</div>

</div>

<script>
function clearSearch() {
    window.location.href = '{% url "assets:warehouse_list" %}';
}

function toggleSelectAll() {
    const selectAllCheckbox = document.getElementById('selectAllHeader');
    const warehouseCheckboxes = document.querySelectorAll('.warehouse-checkbox');
    const isChecked = selectAllCheckbox.checked;
    
    warehouseCheckboxes.forEach(checkbox => {
        checkbox.checked = isChecked;
    });
}

function batchDeleteWarehouses() {
    const checkedBoxes = document.querySelectorAll('.warehouse-checkbox:checked');
    
    if (checkedBoxes.length === 0) {
        alert('请选择要删除的仓库');
        return;
    }
    
    const warehouseNames = Array.from(checkedBoxes).map(checkbox => {
        const row = checkbox.closest('tr');
        return row.querySelector('strong').textContent;
    });
    
    if (confirm(`确定要删除以下 ${checkedBoxes.length} 个仓库吗？\n\n${warehouseNames.join(', ')}\n\n此操作不可撤销！`)) {
        document.getElementById('batchDeleteForm').submit();
    }
}

// 监听单个复选框变化，更新全选状态
document.addEventListener('DOMContentLoaded', function() {
    const warehouseCheckboxes = document.querySelectorAll('.warehouse-checkbox');
    const selectAllHeader = document.getElementById('selectAllHeader');
    
    warehouseCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            const checkedCount = document.querySelectorAll('.warehouse-checkbox:checked').length;
            const totalCount = warehouseCheckboxes.length;
            
            if (selectAllHeader) selectAllHeader.checked = checkedCount === totalCount;
        });
    });
});

// ========= 弹窗创建/编辑（AJAX） =========
(function(){
  function initWhenBootstrapReady(){
    if (!(window.bootstrap && window.bootstrap.Modal)) {
      let tries = 0;
      const timer = setInterval(function(){
        if (window.bootstrap && window.bootstrap.Modal) {
          clearInterval(timer);
          init();
        } else if (++tries > 200) { // ~10s 超时
          clearInterval(timer);
          console.error('Bootstrap not loaded, modal init skipped');
        }
      }, 50);
      window.addEventListener('load', function(){
        if (window.bootstrap && window.bootstrap.Modal) {
          try { init(); } catch(e){}
        }
      }, { once: true });
      return;
    }
    init();
  }

  function init(){
    if (window.__WAREHOUSE_MODAL_INIT__) return; // 避免重复初始化
    window.__WAREHOUSE_MODAL_INIT__ = true;
    const modalEl = document.getElementById('warehouseFormModal');
    if (!modalEl) return;
    const modal = new bootstrap.Modal(modalEl);
    const formTitleEl = document.getElementById('warehouseFormTitle');
    const formBodyEl = document.getElementById('warehouseFormBody');
    const formEl = document.getElementById('warehouseForm');
    let submitting = false;

    function getCsrfToken() {
      const input = document.querySelector('input[name=csrfmiddlewaretoken]');
      if (input && input.value) return input.value;
      const m = document.cookie.match(/csrftoken=([^;]+)/);
      return m ? decodeURIComponent(m[1]) : '';
    }

    async function openFormModal(url, title){
      formTitleEl.textContent = title || '表单';
      formBodyEl.innerHTML = '<div class="text-center text-muted py-3">加载中...</div>';
      formEl.setAttribute('action', url);
      try {
        const resp = await fetch(url, { headers: { 'X-Requested-With': 'XMLHttpRequest' } });
        const data = await resp.json();
        if (data.success) {
          formBodyEl.innerHTML = data.html || '<div class="text-danger">未返回表单内容</div>';
        } else {
          formBodyEl.innerHTML = '<div class="text-danger">加载失败</div>';
        }
      } catch (e) {
        formBodyEl.innerHTML = '<div class="text-danger">加载失败</div>';
      }
      modal.show();
    }

    document.getElementById('btnOpenCreateModal')?.addEventListener('click', function(e){
      e.preventDefault();
      openFormModal(this.getAttribute('data-modal-url'), this.getAttribute('data-modal-title'));
    });

    formEl.addEventListener('submit', async function(e){
      e.preventDefault();
      if (submitting) return; // 防重复提交
      submitting = true;
      const submitBtn = formEl.querySelector('button[type="submit"]');
      const cancelBtn = formEl.querySelector('button[data-bs-dismiss="modal"]');
      if (submitBtn) { submitBtn.disabled = true; submitBtn.dataset.originalText = submitBtn.innerHTML; submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>提交中...'; }
      if (cancelBtn) { cancelBtn.disabled = true; }
      const url = this.getAttribute('action');
      const formData = new FormData(this);
      try {
        const resp = await fetch(url, {
          method: 'POST',
          headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'X-CSRFToken': getCsrfToken(),
          },
          body: formData,
        });
        const data = await resp.json();
        if (resp.ok && data.success) {
          modal.hide();
          window.location.reload();
        } else {
          formBodyEl.innerHTML = data.html || '<div class="alert alert-danger">提交失败</div>';
        }
      } catch (err) {
        formBodyEl.innerHTML = '<div class="alert alert-danger">提交异常</div>';
      } finally {
        submitting = false;
        if (submitBtn) { submitBtn.disabled = false; submitBtn.innerHTML = submitBtn.dataset.originalText || '保存'; }
        if (cancelBtn) { cancelBtn.disabled = false; }
      }
    });
  }

  // 延迟至 Bootstrap 可用再初始化
  initWhenBootstrapReady();
})();
</script>
{% endblock %}